package com.atguigu.gmall.order.interceptor;

import com.atguigu.gmall.order.pojo.UserInfo;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Data
@Component
//@Scope("prototype")
public class LoginInterceptor implements HandlerInterceptor {

    // private UserInfo userInfo;
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Long userId = Long.valueOf(request.getHeader("userId"));
        String username = request.getHeader("username");


        THREAD_LOCAL.set(new UserInfo(userId, null, username));

        return true;
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 由于使用的是tomcat线程池，所以请求结束，线程并没有结束，必须手动调用remove方法，释放ThreadLocal中的资源，否则可能导致OOM
        THREAD_LOCAL.remove();
    }
}
